package com.mssh.login.controller;

import com.alibaba.fastjson.JSONObject;
import com.mssh.entity.table.SysResource;
import com.mssh.login.dto.UserDto;
import com.mssh.login.service.MenusService;
import com.mssh.login.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 熳殊沙华
 * @Date: 2022/11/29/16:32
 * @Description:  用户信息controller层
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private Logger logger = LogManager.getLogger(this.getClass());

    @Autowired
    private UserService userService;

    @Autowired
    private MenusService menusService;

    /**
     * 查询用户信息
     * @param userDto
     * @return
     */
    @PostMapping("/userInfo")
    public JSONObject userInfo(@RequestBody UserDto userDto){
        logger.info("开始查询用户信息，当前用户账号为：{}", userDto.getAccount());
        JSONObject returnMap = new JSONObject();
        try {
            JSONObject result = userService.getUserByAccount(userDto.getAccount());
            if("0000".equals(result.getString("errCode"))){
                //判断是否需要查询资源信息
                if(userDto.isMenuFlag() == true){
                    List<SysResource> menus = menusService.findResourceByUserId((Long) result.getJSONObject("user").get("userId"));
                    returnMap.put("menus", menus);
                    logger.info("资源信息：{}", JSONObject.toJSONString(menus));
                }
                result.getJSONObject("user").remove("userId");
                returnMap.put("userInfo", result.getJSONObject("user"));
                returnMap.put("errCode","0000");
                returnMap.put("errMsg","SUCCESS");
            }else{
                returnMap.put("errCode", result.getString("errCode"));
                returnMap.put("errMsg", result.getString("errMsg"));
            }
        }catch (Exception e){
            logger.warn("客户信息查询异常：{}", e);
            returnMap.put("errCode","9999");
            returnMap.put("errMsg", "客户信息查询异常!");
        }
        return returnMap;
    }

}
